package cn.iocoder.yudao.module.trade.order.service.handler;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.thirdparty.zxhx.ZXHXApiClientFactory;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderDO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.order.service.ZXHXOrderSyncService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.module.api.supply.ConfigConstants.SUPPLY_NAME_ZXHX;

/**
 * 甄新汇选供应链订单的 {@link TradeOrderHandler} 实现类
 *
 * @author 山野羡民
 */
@Slf4j
@Component
public class ZxhxSupplyOrderHandler implements TradeOrderHandler {
    @Resource
    private ZXHXOrderSyncService zxhxOrderSyncService;

    @Override
    public void beforeOrderCreate(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        Set<Long> supplyRelatedSkuIds = orderItems.stream().filter(item -> item.getSupplyRelatedSkuId() != null && item.getSupplyRelatedSkuId() > 0).map(TradeOrderItemDO::getSupplyRelatedSkuId).collect(Collectors.toSet());
        if (CollUtil.isEmpty(supplyRelatedSkuIds)) {
            return;
        }
        Double accountBalance = ZXHXApiClientFactory.tradeClient().getAccountBalance();
        Assertions.isTrue(accountBalance >= order.getPayPrice(), "平台供应链账户余额不足，无法下单");
        order.setSupplyName(SUPPLY_NAME_ZXHX);
    }

    @Override
    public void afterPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        Set<Long> supplyRelatedSkuIds = orderItems.stream().filter(item -> item.getSupplyRelatedSkuId() != null && item.getSupplyRelatedSkuId() > 0).map(TradeOrderItemDO::getSupplyRelatedSkuId).collect(Collectors.toSet());
        if (CollUtil.isEmpty(supplyRelatedSkuIds)) {
            return;
        }
        log.debug("[afterPayOrder][支付成功后需要同步创建第三方供应链订单(supplyRelatedSkuIds={})]", supplyRelatedSkuIds);
        try {
            zxhxOrderSyncService.createOrderWhenPaid(order, orderItems);
        } catch (Exception e) {
            log.error("[afterPayOrder][支付成功后同步创建第三方供应链订单(supplyRelatedSkuIds={})失败]", supplyRelatedSkuIds, e);
        }
    }

    @Override
    public void afterCompleteOrder(TradeOrderDO order) {
        if (CollUtil.isEmpty(order.getSupplyRelatedNos())) {
            return;
        }
        log.debug("[afterCompleteOrder][订单完成后需要同步完成第三方供应链订单(supplyRelatedNos={})]", order.getSupplyRelatedNos());
        for (String supplyRelatedNo : order.getSupplyRelatedNos()) {
            ZXHXApiClientFactory.tradeClient().confirmReceivedOrder(supplyRelatedNo);
        }
    }

}
